package com.ruoyi.web.interceptor;

import com.ruoyi.core.config.GlobalProperties;
import com.ruoyi.core.util.RequestContextUtil;
import com.ruoyi.web.threadLocal.ThreadCache;
import com.ruoyi.web.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

    private GlobalProperties globalProperties;

    public SessionInterceptor(GlobalProperties globalProperties) {
        this.globalProperties = globalProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("================SessionInterceptor-preHandle-[" + RequestContextUtil.getRequestUrl(request) + "]================");

        ThreadCache.initRequestContext();

        String requestUrl = RequestContextUtil.getRequestUrl(request);
        if (isStaticPath(requestUrl)) {
            //ignore
        } else if (isIgnorePath(requestUrl)) {
            //ignore
        } else {
            String token = RequestContextUtil.getToken(request);
            JwtUtil.checkToken(token);
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("================SessionInterceptor-afterCompletion-[" + RequestContextUtil.getRequestUrl(request) + "]================");

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

        ThreadCache.removeAll();
    }


    /**
     * 是否静态目录
     *
     * @param url
     * @return
     */
    private boolean isStaticPath(String url) {
        String[] paths = {"/admin", "/flow"};
        for (String path : paths) {
            if (url.startsWith(concat(globalProperties.getContextPath(), path))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否忽略的地址
     *
     * @param url
     * @return
     */
    private boolean isIgnorePath(String url) {
        String[] paths = {"/login/getAuthCode", "/login/login", "/login/logout", "/error", "/"};
        for (String path : paths) {
            if (url.equals(concat(globalProperties.getContextPath(), path))) {
                return true;
            }
        }
        return false;
    }

    private String concat(String... str) {
        StringBuilder sb = new StringBuilder();
        for (String s : str) {
            if (s != null) {
                sb.append(s);
            }
        }
        return sb.toString();
    }

}
